//
//  IssueDetialCommentViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/26.
//


import UIKit
import MJRefresh
import PKHUD
import UITableView_FDTemplateLayoutCell


/// issue 评论控制器
class IssueDetialCommentViewController: BaseViewController {

   
    var noteTableView:UITableView!
    var cellID = "notecellid"
    var issueModel:IssueModel?
    var noteArray:[NoteModel]?
    var currentPage = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
    
    init(issue: IssueModel) {
        super.init(nibName: nil, bundle: nil)
        self.issueModel = issue
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.loadData(page: 1)
    }
}


// MARK: - 设置界面
extension IssueDetialCommentViewController {
    
    func setupUI(){
        self.title = "评论"
        var fra = view.bounds
        fra.size.height -= Common.topHeight
        noteTableView = UITableView(frame: fra)
        noteTableView.register(UINib.init(nibName: "IssueCommentTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        view.addSubview(noteTableView)
        noteTableView.delegate = self
        noteTableView.dataSource = self
        noteTableView.separatorStyle = .none
        
        let mjH = MJRefreshNormalHeader {
            self.currentPage = 1
            self.loadData(page: self.currentPage)
        }
        mjH?.lastUpdatedTimeLabel.isHidden = true
        noteTableView.mj_header = mjH
        mjH?.beginRefreshing()
        
        let mjF = MJRefreshBackNormalFooter {
            self.currentPage += 1
            self.loadData(page: self.currentPage)
        }
        noteTableView.mj_footer = mjF
        
        noteTableView.emptyDataSetSource = self
        noteTableView.emptyDataSetDelegate = self
        
        if #available(iOS 13.0, *) {
            noteTableView.backgroundColor = Colors.backgroundColor
        }
        
    }
}


extension IssueDetialCommentViewController {
    
  
    
    func loadData(page: Int){
        
        let url = URLs.V3URL + URLs.PROJECTS + self.issueModel!.project_id.description + "/issues/\( self.issueModel!.id!.description)/notes?page=\(self.currentPage)"
        // NSString *strUrl = [NSString stringWithFormat:@"%@%@/%@/issues/%lld/notes?private_token=%@&&page=%lu", GITAPI_HTTPS_PREFIX, GITAPI_PROJECTS, _projectNameSpace, _issue.issueId, [Tools getPrivateToken], (unsigned long)page];
       
        
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<[NoteModel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
            
            DispatchQueue.main.async {
                if result.code == 0 {
                    if page == 1 {
                        self.noteArray = result.data as? [NoteModel]
                    }else {
                        self.noteArray?.append(contentsOf: (result.data as? [NoteModel])!)
                        if result.data?.count == 0 {
                            self.noteTableView.mj_footer.endRefreshingWithNoMoreData()
                            return
                        }
                    }
                    self.noteTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
                self.noteTableView.mj_header.endRefreshing()
                self.noteTableView.mj_footer.endRefreshing()
            }
        }
    }
}


extension IssueDetialCommentViewController: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.noteArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.noteArray![indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! IssueCommentTableViewCell
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.fd_heightForCell(withIdentifier: cellID) { (cell) in
            
            (cell as! IssueCommentTableViewCell).model = self.noteArray![indexPath.row]
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
}

extension IssueDetialCommentViewController: JXPagingViewListViewDelegate {
    public func listView() -> UIView {
        return self.view
    }
    
    public func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }

    public func listScrollView() -> UIScrollView {
        return self.noteTableView
    }
}
